<template>
  <div>
    <el-dialog :title="dialog.title" :visible.sync="dialogVisible" width="60%" @open="dialogOpen">
      <el-form ref="form" :model="form" :rules="formRuler" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="province" prop="province">
              <el-select v-model="form.province" placeholder="province" size="small" @change="provinceChange">
                <!--suppress JSUnresolvedVariable -->
                <el-option v-for="item in provinceList" :key="item.provinceId"
                           :label="item.provinceName" :value="item.provinceId"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="city" prop="city">
              <el-select v-model="form.city" placeholder="city" size="small" @change="cityChange">
                <el-option v-for="item in cityList" :key="item.id" :label="item.cityName" :value="item.cityId"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="county" prop="county">
              <el-select v-model="form.county" placeholder="county" size="small">
                <el-option v-for="item in countyList" :key="item.id" :label="item.countyName" :value="item.countyId"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="detail" prop="detail">
              <el-input v-model="form.detail" placeholder="detail" maxlength="64" size="small"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="username" prop="username">
              <el-input v-model="form.username" placeholder="username" maxlength="8" size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="phone" prop="phone">
              <el-input v-model="form.phone" placeholder="phone" maxlength="11" size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="postal" prop="postal">
              <el-input v-model="form.postal" placeholder="postal" maxlength="6" size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="remark" prop="remark">
              <el-input v-model="form.remark" placeholder="remark" maxlength="64" size="small"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer">
        <el-row :gutter="64" type="flex" justify="end">
          <el-button type="info" @click="reset">清空</el-button>
          <el-button type="info" v-if="dialog.id > 0" @click="removeAddress" :loading="removeLoading">删除</el-button>
          <el-col :span="4">
            <el-button type="primary" @click="dialog.submitClick"
                       :loading="submitLoading">{{dialog.submitLabel}}</el-button>
          </el-col>
        </el-row>
      </span>
    </el-dialog>
    <div class="wrapper" style="padding: 24px 8px">
      <span class="title">
        The following addresses will be used on the checkout page by default.
        <el-button type="text" @click="addNew">Add New</el-button>
      </span>
      <el-row class="address" :gutter="40" v-loading="initLoading">
        <el-col :span="8" v-for="item in address" :key="item.id">
          <!--suppress RequiredAttributes -->
          <xum-address v-bind='item' @edit='handEdit'/>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import XumAddress from '@/components/general/XumAddress'
import {
  deleteUserAddressById,
  insertUserAddress, queryAddressById,
  queryAllUserAddress,
  queryCitiesByProvince,
  queryCountiesByCity,
  queryProvinces, updateUserAddressById
} from '@/api/ApiUserAddress'
import constants from '@/constants'
import UserAddressInsertDTO from '@/api/entity/UserAddressInsertDTO'
import UserAddressChgDTO from '@/api/entity/UserAddressChgDTO'
import Utils from '@/utils/Utils'

export default {
  name: 'AccountAddress',
  components: {
    'xum-address': XumAddress
  },
  data () {
    return {
      initLoading: true,
      dialogVisible: false,
      submitLoading: false,
      removeLoading: false,
      dialog: {
        id: 0,
        title: '编辑地址',
        submitLabel: '提交修改',
        submitClick: () => {
          const vm = this
          alert(JSON.stringify(this.provinceList.find(item => {
            return item.id === vm.form.province
          })))
        }
      },
      provinceList: [],
      cityList: [],
      countyList: [],
      form: {
        province: '',
        city: '',
        county: '',
        detail: '',
        postal: '',
        phone: '',
        username: '',
        remark: ''
      },
      formRuler: {
        province: [
          { required: true, message: 'province不能为空', trigger: 'blur' }
        ],
        city: [
          { required: true, message: 'city不能为空', trigger: 'blur' }
        ],
        county: [
          { required: true, message: 'county不能为空', trigger: 'blur' }
        ],
        detail: [
          { required: true, message: '详细地址信息不能为空', trigger: 'blur' },
          { max: 64, min: 4, message: '详细地址信息为4-64个字符', trigger: 'blur' }
        ],
        postal: [
          { pattern: '^[0-9]{6}$', message: '不是正确的邮编', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '联系方式不能为空', trigger: 'blur' },
          {
            pattern: '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\\d|9\\d)\\d{8}$',
            message: '不是合法的手机号码',
            trigger: 'blur'
          }
        ],
        username: [
          { required: true, message: '联系人不能为空', trigger: 'blur' },
          { min: 0, max: 8, message: '联系人姓名不能超过8个字符' }
        ]
      },
      address: []
    }
  },
  methods: {
    /**
       * 新增收货地址，打开对话框
       */
    addNew () {
      const vm = this
      this.fillDialog(this, 0, () => {
        vm.dialogVisible = true
      })
    },
    /**
       * 编辑收货地址，打开对话框
       * @param address 地址id
       */
    handEdit (address) {
      const vm = this
      vm.fillDialog(vm, address.id, () => {
        vm.dialogVisible = true
      })
    },
    /**
       * 填充地址对话框
       * @param vm vm
       * @param {Number} address 地址id，大于0时查询地址数据并填充，小于等于0时表示添加地址数据，重置对话框
       * @param {Function} callback 回调
       */
    fillDialog (vm, address, callback = null) {
      if (address <= 0) {
        // 新增数据
        vm.reset()
        vm.dialog.id = 0
        vm.dialog.title = '添加地址'
        vm.dialog.submitLabel = '提交'
        vm.dialog.submitClick = vm.addAddress
        if (callback !== null && typeof callback === 'function') {
          callback()
        }
      } else {
        // 编辑数据
        vm.dialog.id = address
        vm.dialog.title = '编辑地址'
        vm.dialog.submitLabel = '修改'
        vm.dialog.submitClick = vm.updateAddress
        // 获取地址详细信息
        queryAddressById(address, data => {
          if (data.code === constants.resultCode.OK) {
            if (data.object === null) {
              vm.$message.error('地址信息不存在')
              return
            }
            const a = data.object
            Promise.all([
              new Promise(resolve => {
                queryCitiesByProvince(a.provinceId, data => {
                  if (constants.resultCode.OK === data.code) {
                    vm.cityList = data.object
                    resolve('')
                  } else {
                    resolve(data.message)
                  }
                })
              }),
              new Promise(resolve => {
                queryCountiesByCity(a.cityId, data => {
                  if (constants.resultCode.OK === data.code) {
                    vm.countyList = data.object
                    resolve('')
                  } else {
                    resolve(data.message)
                  }
                })
              })
            ]).then(data => {
              data = data.filter(v => v.trim().length > 0)
              const m = data.length > 0
              if (!m) {
                // 赋值
                vm.form.province = a.provinceId
                vm.form.city = a.cityId
                vm.form.county = a.countyId
                vm.form.detail = a.detail
                vm.form.username = a.username
                vm.form.postal = a.postalCode
                vm.form.phone = a.phone
                vm.form.remark = a.remark
                if (callback !== null && typeof callback === 'function') {
                  callback()
                }
              }
            })
          }
        })
      }
    },
    /**
       * 对话框打开前回调，获取province数据
       */
    dialogOpen () {
      const vm = this
      if (vm.provinceList.length === 0) {
        queryProvinces(data => {
          if (data.code === constants.resultCode.OK) {
            vm.provinceList = data.object
          }
        })
      }
    },
    /**
     * 联动 province -> city
     */
    provinceChange (provinceId) {
      const vm = this
      // noinspection JSUnresolvedVariable
      queryCitiesByProvince(provinceId, data => {
        if (constants.resultCode.OK === data.code) {
          vm.form.city = ''
          vm.form.county = ''
          vm.countyList = []
          vm.cityList = data.object
        }
      })
    },
    /**
     * 联动 city -> county
     */
    cityChange (cityId) {
      const vm = this
      queryCountiesByCity(cityId, data => {
        if (constants.resultCode.OK === data.code) {
          vm.form.county = ''
          vm.countyList = data.object
        }
      })
    },
    /**
     * 重置表单数据
     */
    reset () {
      this.form = {
        province: '',
        city: '',
        county: '',
        detail: '',
        postal: '',
        phone: '',
        username: '',
        remark: ''
      }
      this.cityList = []
      this.countyList = []
    },
    /**
     * 添加地址
     */
    addAddress () {
      const vm = this
      vm.submitLoading = true
      const userAddressInsertDTO = new UserAddressInsertDTO()
      const provinceName = Utils.find(vm.provinceList, v => v.provinceId === vm.form.province).provinceName
      const cityName = Utils.find(vm.cityList, v => v.cityId === vm.form.city).cityName
      const countyName = Utils.find(vm.countyList, v => v.countyId === vm.form.county).countyName
      userAddressInsertDTO
        .setProvinceId(vm.form.province).setProvinceName(provinceName)
        .setCityId(vm.form.city).setCityName(cityName)
        .setCountyId(vm.form.county).setCountyName(countyName)
        .setDetail(vm.form.detail)
        .setPhone(vm.form.phone)
        .setPostalCode(vm.form.postal)
        .setIsDefault(0)
        .setUsername(vm.form.username)
        .setRemark(vm.form.remark)
        .setName('')
      insertUserAddress(userAddressInsertDTO, () => {
        vm.$message.success('添加地址成功')
        vm.dialogVisible = false
        // 刷新列表
        vm.refreshList()
      }, () => {
        vm.submitLoading = false
      })
    },
    /**
       * 删除一个地址信息
       */
    removeAddress () {
      const vm = this
      vm.removeLoading = true
      deleteUserAddressById(vm.dialog.id, data => {
        if (data.code === constants.resultCode.OK) {
          vm.$message.success('删除地址成功')
          vm.dialogVisible = false
          // 刷新列表
          vm.refreshList()
        }
      }, () => {
        vm.removeLoading = false
      })
    },
    /**
       * 更新地址信息，在更新对话框中调用
       */
    updateAddress () {
      const vm = this
      vm.submitLoading = true
      const userAddressChgDTO = new UserAddressChgDTO()
      const provinceName = Utils.find(vm.provinceList, v => v.provinceId === vm.form.province).provinceName
      const cityName = Utils.find(vm.cityList, v => v.cityId === vm.form.city).cityName
      const countyName = Utils.find(vm.countyList, v => v.countyId === vm.form.county).countyName
      userAddressChgDTO
        .setId(vm.dialog.id)
        .setProvinceId(vm.form.province).setProvinceName(provinceName)
        .setCityId(vm.form.city).setCityName(cityName)
        .setCountyId(vm.form.county).setCountyName(countyName)
        .setDetail(vm.form.detail)
        .setPhone(vm.form.phone)
        .setPostalCode(vm.form.postal)
        .setIsDefault(0)
        .setUsername(vm.form.username)
        .setRemark(vm.form.remark)
        .setName('')
      updateUserAddressById(userAddressChgDTO, () => {
        vm.$message.success('修改地址成功')
        vm.dialogVisible = false
        // 刷新列表
        vm.refreshList()
      }, () => {
        vm.submitLoading = false
      })
    },
    /**
       * 刷新地址列表
       */
    refreshList () {
      const vm = this
      vm.initLoading = true
      queryAllUserAddress(data => {
        if (data && data.code === constants.resultCode.OK && data.object) {
          let item
          let index = 0
          for (let i = 0; i < data.object.length; i++) {
            item = data.object[i]
            item.name = item.username
            item.province = item.provinceName
            item.city = item.cityName
            item.county = item.countyName
            // noinspection JSUnresolvedVariable
            item.town = item.townName
            // noinspection JSUnresolvedVariable
            item.village = item.villageName
            item.title = item.isDefault === 1 ? '默认地址' : '地址' + (++index)
          }
        }
        vm.address = data.object
      }, () => {
        vm.initLoading = false
      })
    }
  },
  mounted () {
    // 在打开地址信息页面时获取地址信息
    this.refreshList()
  }
}
</script>

<style lang="scss" scoped>
  .wrapper {
    text-align: left;
    padding-top: 8px;

    .title {
      user-select: none;
      margin-bottom: 16px;
    }

    .address {
      margin-top: 24px;
      display: block;
      width: 100%;
    }

  }
</style>
